//
//  ConPersonalController.m
//  Shengzhuli
//
//  Created by FXGuo on 17/3/19.
//  Copyright © 2017年 kamangkeji. All rights reserved.
//

#import "ConPersonalController.h"
#import "PersonInfoCell.h"
#import "PersonTableViewCell.h"

#import "SZLPersonInfoViewController.h"
#import "BuyCarsViewController.h"
#import "ConEditCardViewController.h"
#import "ConIdentifyViewController.h"
#import "ConPeronalSetViewController.h"
#import "SZLAccountHelper.h"
#import "PersonNetWork.h"
#import "MBProgressHUD+MJ.h"

#import "SZLSingleListViewController.h"
#import "SZLReceiveAddressViewController.h"
#import "SZLMykeepViewController.h"
#import "ShareTool.h"
#import "ThirdConfig.h"
#import "UIAlertView+Entension.h"
#import "ContactListViewController.h"
#import "ConMyClubEditViewController.h"
#import "ConIntegralController.h"
#import "SZLTabBarViewController.h"
#import "ChatViewController.h"
#import "ConpickUpViewController.h"
#import "ConAlreadyAdderViewController.h"
#import "ConActiveValueController.h"
#import "YueStatusViewController.h"
#import "SZLAccountViewController.h"
#import "ZhujiaoListController.h"

@interface ConPersonalController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray *titles;
@property (nonatomic,strong) PersonInfo *info;
@property (nonatomic, strong) NSString *portraitUrl;
//消息未读数
@property (nonatomic,assign) NSInteger unreadCount;

@end

@implementation ConPersonalController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setNav];
    [self setUpView];
    //[self getUnreadCount];
    //注册通知获取未读消息
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getUnreadCount) name:KPersongbadgeUpdate object:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getPersonInfo];
    });
}
- (void)setNav
{
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
#pragma mark --------------------------------------------------------
    UIButton *messageBtn = [[UIButton alloc]init];
    messageBtn.frame = CGRectMake(0, 0, 25,25);
    [messageBtn setImage:GetImage(@"whiteCar") forState:UIControlStateNormal];
    [messageBtn addTarget:self action:@selector(rightItemClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -10;
    
    self.navigationItem.rightBarButtonItems = @[negativeSpacer,[[UIBarButtonItem alloc]initWithCustomView:messageBtn]];
}
- (void)rightItemClick
{
    BuyCarsViewController *carVc = [[BuyCarsViewController alloc]init];
    [self.navigationController pushViewController:carVc animated:YES];
}
//统计未读消息
- (void)getUnreadCount
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    self.unreadCount = unreadCount;
    [self.tableView reloadData];
}
- (void)setUpView
{
    [self.view addSubview:self.tableView];
//    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, -298, ScreenW, 500)];
//    imageView.backgroundColor = RGBColor(59, 58, 63);
//    imageView.contentMode = UIViewContentModeScaleAspectFill;
//    [self.tableView insertSubview:imageView atIndex:0];
}
- (void)configTitles
{
    if (self.info.roleId == RoleTypeExperVIP) {//体验式
        self.titles = @[@[@"我的账户",@"我的订单",@"收货地址",@"我与大咖"],@[@"捡漏专区",@"活跃值",@"我的人脉",@"我的积分"],@[@"我的关注",@"在线客服"]];
    }else {
        self.titles = @[@[@"我的账户",@"我的订单",@"收货地址",@"我与大咖"],@[@"捡漏专区",@"活跃值",@"我的人脉"],@[@"我的关注",@"在线客服"]];
    }
    //是否是助教
    if (self.info.isTeach) {
        if (self.info.roleId == RoleTypeExperVIP) {//体验式
            self.titles = @[@[@"我的账户",@"我的订单",@"收货地址",@"我与大咖",@"助教管理"],@[@"捡漏专区",@"活跃值",@"我的人脉",@"我的积分"],@[@"我的关注",@"在线客服"]];
        }else {
            self.titles = @[@[@"我的账户",@"我的订单",@"收货地址",@"我与大咖",@"助教管理"],@[@"捡漏专区",@"活跃值",@"我的人脉"],@[@"我的关注",@"在线客服"]];
        }
    }
}
#pragma mark - Table view data delegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 121;
    }
    return 50;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.titles.count+1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return [self.titles[section-1] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        PersonInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PersonInfoCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.info = self.info;
        cell.layer.borderWidth = 0;
        __WEAK
        cell.btnClickBlock = ^(PersonInfoType type){
            switch (type) {
                case PersonInfoTypeChange:
                {
                    SZLPersonInfoViewController *personVc = [[SZLPersonInfoViewController alloc]init];
                    personVc.info = self.info;
                    [weakSelf.navigationController pushViewController:personVc animated:YES];
                }
                    break;
                case PersonInfoTypeCard:
                {
                    ConEditCardViewController *cardVc = [[ConEditCardViewController alloc]init];
                    cardVc.portraitUrl = self.portraitUrl;
                    cardVc.type = EditTypeShowSelf;
                    [weakSelf.navigationController pushViewController:cardVc animated:YES];
                }
                    break;
                case PersonInfoTypeVIP:
                {
                    if ([SZLAccountHelper shareInstance].roleId == 2) {
                        ConAlreadyAdderViewController *adderVc = [[ConAlreadyAdderViewController alloc]init];
                        [self.navigationController pushViewController:adderVc animated:YES];
                    }else {
                        ConIdentifyViewController *vipVc = [[ConIdentifyViewController alloc] init];
                        [self.navigationController pushViewController:vipVc animated:YES];
                    }
                }
                    break;
                case PersonInfoTypePrivate:
                {
                    ConPeronalSetViewController *setVc = [[ConPeronalSetViewController alloc] init];
                    setVc.allowStutas = self.info.allowStutas;
                    [self.navigationController pushViewController:setVc animated:YES];
                }
                    break;
                case PersonInfoTypeBuyCar:
                {
                    BuyCarsViewController *carVc = [[BuyCarsViewController alloc]init];
                    [self.navigationController pushViewController:carVc animated:YES];
                }
                    break;
                default:
                    break;
            }
        };
        return cell;
    }
    PersonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PersonTableViewCell class])];
    cell.title = self.titles[indexPath.section-1][indexPath.row];
    if (indexPath.section == 2 && indexPath.row == 1) {
        cell.unreadCount = self.info.activeValueAll;
        NSLog(@"self.unreadCount = %ld",(long)self.unreadCount);
    }else {
        cell.unreadCount = 0;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        [self jumpToSingleAddressController:indexPath];
    }else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            ConpickUpViewController *pvc = [[ConpickUpViewController alloc] init];
            pvc.nickName = self.info.nickName;
            [self.navigationController pushViewController:pvc animated:YES];
        }else if (indexPath.row == 1) {
            ConActiveValueController *vc = [[ConActiveValueController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 2){
            [self jumpToContactList];
        }else {
            ConIntegralController *conVc = [[ConIntegralController alloc]init];
            [self.navigationController pushViewController:conVc animated:YES];
        }
    }else if (indexPath.section == 3) {
            [self jumpToFocusServiceController:indexPath];
    }
}
- (void)jumpToSingleAddressController:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        SZLAccountViewController *acountVc = [[SZLAccountViewController alloc]init];
        [self.navigationController pushViewController:acountVc animated:YES];
    }else if (indexPath.row == 1) {
        SZLSingleListViewController *singleVc = [[SZLSingleListViewController alloc]init];
        singleVc.type = SingleTypeUnPay;
        [self.navigationController pushViewController:singleVc animated:YES];
    }else if(indexPath.row == 2){
        SZLReceiveAddressViewController *addressVc = [[SZLReceiveAddressViewController alloc]init];
        addressVc.type = AddressTypeModify;
        [self.navigationController pushViewController:addressVc animated:YES];
    }else if(indexPath.row == 3) {
        YueStatusViewController *yvc = [[YueStatusViewController alloc] init];
        [self.navigationController pushViewController:yvc animated:YES];
    }else {
        ZhujiaoListController *vc = [[ZhujiaoListController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (void)jumpToContactList
{
    ContactListViewController *contactVc = [[ContactListViewController alloc]init];
    [self.navigationController pushViewController:contactVc animated:YES];
    
}
- (void)jumpToFocusServiceController:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        SZLMykeepViewController *keepVc = [[SZLMykeepViewController alloc]init];
        keepVc.type = MyListKeep;
        [self.navigationController pushViewController:keepVc animated:YES];
    }else{
        [self getSerVice];
    }
}

- (void)getPersonInfo
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    [self showClearBgWaiter];
    [PersonNetWork getPersonInfoWithParame:parame response:^(BOOL success, NSString *msg,NSString *errorCode,PersonInfo *info) {
        [self hideWaiter];
        [self hideReloadView];
        if (success) {
            //支付后需要在这更新roleID权限
            [SZLAccountHelper shareInstance].roleId = info.roleId;
            self.info = info;
            self.portraitUrl = self.info.portraitUrl;
            [self configTitles];
            [self.tableView reloadData];
        }else{
            if ([msg isEqualToString:NetworkError]) {
                [self showReloadViewWithTarget:self action:@selector(getPersonInfo)];
            }
            [MBProgressHUD showError:msg toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if ([errorCode isEqualToString:NoLoginStatus]) {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    SZLTabBarViewController *barVc = (SZLTabBarViewController*)[UIApplication sharedApplication].keyWindow.rootViewController;
                    barVc.selectedIndex = 0;
                    [SZLAccountHelper clearAlreadyInfo];
                    [SZLAccountHelper shouldLogin];
                }
            });
        }
    }];
}
- (void)getSerVice
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    [self showClearBgWaiter];
    [PersonNetWork getServiceWithParame:parame response:^(BOOL success, NSString *msg,NSString *service) {
        [self hideWaiter];
        if (success) {
            ChatViewController *chatController = [[ChatViewController alloc]initWithConversationChatter:service conversationType:EMConversationTypeChat];
            chatController.title = @"客服";
            chatController.info = self.info;
            chatController.isHiddenItem = YES;
            EaseUserModel *model = [[EaseUserModel alloc]initWithBuddy:service];
            model.nickname = self.info.nickName;
            model.avatarURLPath = self.info.portraitUrl;
//            model.ID = self.ID;
            chatController.model = model;
            [self.navigationController pushViewController:chatController animated:YES];
        }else {
            [MBProgressHUD showError:msg];
        }
    } ];
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenW,ScreenH-64) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.sectionFooterHeight = 0.01;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = RGBColor(239, 239, 244);
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
        _tableView.separatorInset = UIEdgeInsetsMake(0, 55, 0, 0);
        _tableView.tableFooterView = [[UIView alloc]init];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PersonInfoCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([PersonInfoCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PersonTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([PersonTableViewCell class])];
    }
    return _tableView;
}

@end
